#encoding=utf-8
#接口调用方法，请求对方的
import time
import urllib,traceback
from gm_site import settings
import ProtocolHelper
isTest=0
if not isTest:
     from websys import  fun
     from websys.models import  (ServerInfo)

# server_id = "test1"
# server_url="192.168.0.128:8106"
# server_id = "_5wan1"
# server_url="123.207.52.239:8105"

#获取全部的服信息，{服号:ip:端口,"test1":"192.168.0.128:8106","_5wan1":"123.207.52.239:8105"}
global ServerList
ServerList={}
if not isTest:
     ServerList={}
def initServer():
     if not ServerList:
          tarr=ServerInfo.objects.all().values('pf','host','port')
          for ii_item in tarr:
               ServerList[ii_item['pf']]='%s:%s'%(ii_item['host'],ii_item['port'])
initServer()

#统一接口
CALLID=1
INTERFACE_ID='oss'
#服务器的ip:端口，服号，方法名，参数
def getResult(server_id,funname,params):
     global ServerList
     if server_id not in ServerList:
          return -100,{}

     server_url=ServerList[server_id]
     now_ts = time.time()
     _key = str(CALLID)+":"+str(int(now_ts))#可固定
     data = [{"m":funname,#接口名
          "c":CALLID,
          "p":params,#参数
          "st":now_ts}]
     try:
          url = "http://%s/%s/%s/0?%s|%s"%(server_url,INTERFACE_ID,server_id,_key, urllib.quote(ProtocolHelper.Encode(data, INTERFACE_ID)))
          print("url: {}".format(url))
          ret = urllib.urlopen(url).read()
          print '=============',ret
          result = ProtocolHelper.Decode(ret, INTERFACE_ID)[0]['p']
          print 'getResult--->',result
          #result=[{'p':'data':[],'r':0}] r为0成功
          return result['r'],result
     except:
          if isTest:
               print traceback.format_exc()
          else:
               fun.add_log_err(traceback.format_exc())#后期人工调用
          return -99,{}

def getResult2(server_id, funname, params):
     # global ServerList
     # if server_id not in ServerList:
     #      return -100, {}

     server_url = settings.mz_ip
     now_ts = time.time()
     _key = str(CALLID) + ":" + str(int(now_ts))  # 可固定
     data = [{"m": funname,  # 接口名
              "c": CALLID,
              "p": params,  # 参数
              "st": now_ts}]
     try:
          url = "http://%s/%s/%s/0?%s|%s" % (
          server_url, INTERFACE_ID, server_id, _key, urllib.quote(ProtocolHelper.Encode(data, INTERFACE_ID)))
          print("url: {}".format(url))
          ret = urllib.urlopen(url).read()
          print '=============', ret
          result = ProtocolHelper.Decode(ret, INTERFACE_ID)[0]['p']
          print 'getResult--->', result
          # result=[{'p':'data':[],'r':0}] r为0成功
          return result['r'], result
     except:
          if isTest:
               print traceback.format_exc()
          else:
               fun.add_log_err(traceback.format_exc())  # 后期人工调用
          return -99, {}

# 批量服处理
def getResult_Batch2(ser_arr, params, funname):
     ok_num = 0
     for ii_id in ser_arr:
          code, res = getResult2(ii_id, 'EXTERNAL_' + funname, params)
          print code, '--getResult_Batch--', res
          if code == 0:
               ok_num += 1
     return ok_num


#批量服处理
def getResult_Batch(ser_arr,params,funname):
     ok_num=0
     for ii_id in ser_arr:
          code,res=getResult(ii_id,'EXTERNAL_'+funname,params)
          print code,'--getResult_Batch--',res
          if code==0:
               ok_num+=1
     return ok_num

#某个服务调用返回
def getResult_One(ser_id,params,funname):
     return getResult(ser_id,'EXTERNAL_'+funname,params)

#跑马灯
#ser_arr为服的编号，msgid自增长id,start开始时间，end为结束时间，sort为排序，content=
#msg,platform, msgid, startdate, enddate, sort
#参数: ["内容", "all", int(消息id), int(开始时间戳), int(结束时间戳), int(排序值)]
def ADDSCROLLNOTES(ser_arr,msg,msgid,startdate,enddate,sort,platform='all'):
     # tmsgid = 1
     # start = time.time()
     # end = start + 60#*60*24*7
     # tsort = 1
     # params = ["测试跑马灯：123456（送红包）","all", tmsgid, start, end, tsort]    # 接口参数，顺序需对应
     #params = ["测试跑马灯：123456（送红包）","all", msgid]    # 接口参数不够，顺序不对应
     params=[msg,platform,msgid,startdate,enddate,sort]
     print ser_arr,'--ADDSCROLLNOTES---',params
     return getResult_Batch(ser_arr,params,"ADDSCROLLNOTES")
     #getResult("123.207.52.239:8105","EXTERNAL_ADDSCROLLNOTES",params)
'''
"EXTERNAL_DELSCROLLNOTES"
删除公告
args: [msgid] //公告ID，多条可用逗号分隔
'''
def DELSCROLLNOTES(ser_arr,msgid):
     params=[msgid]
     return getResult_Batch(ser_arr,params,"DELSCROLLNOTES")

'''
封号把控
EXTERNAL_LOGIN_SWITCH_UID
args: [isLogin,uid,_timer]
    封号把控
    @param isLogin: int  登陆允否 1为允许 0为禁止
    @param  uid   :  str 用户id
    @param  _timer : float 时间戳 如果永远封号，设置为-1
'''
def LOGIN_SWITCH_UID(ser_arr,isLogin,uid,_timer):
     params=[isLogin,uid,_timer]
     return getResult_Batch(ser_arr,params,'LOGIN_SWITCH_UID')

'''
禁言管理
EXTERNAL_FORBID_SPEAK
args: [_uid,_timer]
     禁言
    @param uid: str 用户ID
    @param _timer: float 时间戳，可传-1
    '''
def FORBID_SPEAK(ser_arr,uid,_timer):
     params=[uid,_timer]
     return getResult_Batch(ser_arr,params,'FORBID_SPEAK')

'''
管理员发送邮件
EXTERNAL_SENDMAIL
args: [uids,msg,attant,other]
   管理员发送邮件
    @param uids: str uid集合以逗号分割，如果给所有人发，则传"all"
    @param msg: str 邮件信息
    @param attant: dict 附件 {"goldpoint":500}，没有则传None
    @param other:  目前未用到
'''


def SENDMAIL(ser_arr, uids, msg, attant=None, other=''):
     params = [uids, msg, attant, other]
     return getResult_Batch(ser_arr, params, 'SENDMAIL')
'''
查询用户信息
EXTERNAL_USER_INFO
args: [uids]
    查询用户信息
    @param uid: str uid
    '''
def USER_INFO(ser_id,uid):
     params=[uid]
     code,res= getResult_One(ser_id,params,'USER_INFO')
     return {'code':code,'res':res}

'''
模糊查询用户信息
"EXTERNAL_SEARCH_NAME"
args: [target]
    模糊查询用户信息
    @param target :str 查询名字
    '''
def SEARCH_NAME(ser_id,target):
     params=[target]
     code,res= getResult_One(ser_id,params,'SEARCH_NAME')
     return {'code':code,'res':res}





'''
从玩家背包删除道具
"EXTERNAL_DELITEMS"
args: [uids, items]
    从玩家背包删除道具
    @param uids: str uid集合以逗号分割
    @param items: dict 道具信息  数据如：{id: num}
'''
def DELITEMS(ser_arr,uids,items):
     params = [uids,items]
     return getResult_Batch(ser_arr, params, 'DELITEMS')


#保存CDK
"EXTERNAL_SAVE_CDK"
#args: [{cdk: items}]  // items为dict，类似于发邮件的道具参数
def SAVE_CDK(ser_arr,data):
     params = [data]
     return getResult_Batch2(ser_arr, params, 'SAVE_CDK')


#测试
# start = time.time()
# end = start + 60#*60*24*7
# print AddScrollNotes(["_5wan1"],"chong测试跑马灯：123456789（送红包）",2,start,end,12)




